package com.greenline.push.service.core.task;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.PriorityBlockingQueue;

import javax.annotation.Resource;

import org.apache.log4j.Logger;

import com.greenline.push.service.core.ProcessQueueList;
import com.greenline.push.service.core.counter.CounterManager;
import com.greenline.push.service.core.item.Packet;
import com.greenline.push.service.core.utils.Constants;
import com.greenline.push.services.dto.QueueDTO;
import com.greenline.push.web.share.ReceiveStatisticsService;

/**
 * 
 * @Type SendStatisticsDataSchedule
 * @Desc 队列统计任务
 * @author shuai.zuo
 * @date 2014年11月17日
 * @Version V1.0
 */
public class SendStatisticsDataSchedule {
    @Resource
    private CounterManager countManager;
    @Resource
    private ReceiveStatisticsService monitorService;
    private Logger logger = Constants.LOG_TONGJI;
    private Timer t;

    // 主要统计队列的数据
    public void startTask() {
        // test if running
        if (t != null) {
            t.cancel();
        }
        t = new Timer();
        t.schedule(new TimerTask() {
            @Override
            public void run() {
                ConcurrentHashMap<String, ProcessQueueList> tmp = countManager.getQueueMap();
                List<QueueDTO> queueList = new ArrayList<QueueDTO>();
                for (Map.Entry<String, ProcessQueueList> entry : tmp.entrySet()) {
                    QueueDTO tmpdto = new QueueDTO();
                    tmpdto.setQueueName(entry.getKey());
                    ProcessQueueList s = entry.getValue();
                    List<PriorityBlockingQueue<Packet>> b = s.getProcessQueueList();
                    Integer total = 0;
                    for (int i = 0; i < b.size(); i++) {
                        total += b.get(i).size();
                    }
                    tmpdto.setCount(total);
                    queueList.add(tmpdto);
                }

                monitorService.ReceiveQueueStatus(Constants.APP_KEY, queueList);
                logger.debug(String.format("%s完成统计数据发送***", Constants.APP_KEY));
            }
        }, new Date(), 2000);
        logger.debug("统计任务开启成功***" + Constants.APP_KEY);
    }

    public boolean stopTask() {
        if (t == null) {
            logger.debug("统计任务关闭成功***" + Constants.APP_KEY);
            return false;
        }
        t.cancel();
        logger.debug("统计任务关闭成功***" + Constants.APP_KEY);
        return true;
    }
}
